import cPickle
from PyQt4 import QtGui, Qt, QtCore
from PyQt4 import QtWebKit
from pluginsystem.plugin_system import get_plugin_by_keyword

class Viewer(QtGui.QTabWidget):
    def __init__(self, parent = None):
        QtGui.QTabWidget.__init__(self, parent)
        
    def showItemByIndex(self, index):
        if index.child(0,0).data().isNull():
            keyword = str(index.data().toString())
            plugin = get_plugin_by_keyword(keyword)
            parent = index.parent()
            config = cPickle.loads(str(parent.data(Qt.Qt.UserRole + 1).toString()))
            filename = plugin.get_file(config)
            file = QtCore.QFile(filename)
            file.open(QtCore.QFile.ReadOnly)
            filestream = QtCore.QTextStream(file)
            
            if plugin.get_mime_type() == "TEXT/PLAIN":
                tab = QtGui.QTextEdit()
                self.addTab(tab, self.tr(plugin.get_doc_name(config)))
                tab.setPlainText(filestream.readAll())
            else:
                tab = QtWebKit.QWebView()
#                tab = QtGui.QTextBrowser()
                self.addTab(tab, self.tr(plugin.get_doc_name(config)))
                tab.load(QtCore.QUrl("file://" + filename))
        else:
            print "program"